package com.bwie.filter;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.concurrent.TimeUnit;

/**
 * @Author: lrz
 * @Date: 2024/10/31 15:15
 * @Description:
 **/
@Configuration
public class MyFilter implements GlobalFilter, Ordered {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        String url = request.getURI().getPath();
        String api = request.getRemoteAddress().getAddress().toString();
        if(url.contains("login")) {
            return chain.filter(exchange);
        }
        if(api.contains("192.168.80.192")){
            return chain.filter(exchange);
        }

        String token = request.getHeaders().getFirst("token");
        if(token==null){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        Claims body = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody();
        Integer userId = body.get("userId",Integer.class);
        String key = "token:"+userId;
        String redisToken = stringRedisTemplate.opsForValue().get(key);
        if(redisToken==null||!redisToken.equals(token)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        stringRedisTemplate.expire(key,30, TimeUnit.MINUTES);

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
